package com.helmlabs.grouper.accounts.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.helmlabs.grouper.accounts.model.UserProfile;
import com.helmlabs.grouper.search.service.IndexerServiceFactory;

public class UserProfileDaoHibernate extends HibernateDaoSupport implements UserProfileDao {
	
	public UserProfile save(UserProfile userProfile){
		if (userProfile!=null){
			if (userProfile.getId()==null){
				Long id = (Long)getHibernateTemplate().save(userProfile);
				userProfile.setId(id);
				IndexerServiceFactory.getIndexerService().index(userProfile);
			} else {
				getHibernateTemplate().update(userProfile);
				IndexerServiceFactory.getIndexerService().remove(userProfile);
				IndexerServiceFactory.getIndexerService().index(userProfile);
			}
		}
		return userProfile;
	}
	
	public UserProfile get(Long id){
		return (UserProfile)getHibernateTemplate().get(UserProfile.class, id);
	}
	
	public UserProfile getByUsername(String username){
		DetachedCriteria criteria = DetachedCriteria.forClass(UserProfile.class);
		criteria.add(Restrictions.eq("username", username));
		List<UserProfile> profiles = getHibernateTemplate().findByCriteria(criteria, 0, 1);
		if (profiles!=null && profiles.size()>0){
			return profiles.get(0);
		}
		
		return null;
	}

	public List<UserProfile> getAll(int page, int pageSize, String sort,
			String order) {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserProfile.class);
		if (order!=null){
			if (order.equals("asc")){
				criteria.addOrder(Order.asc(sort));
			} else {
				criteria.addOrder(Order.desc(sort));
			}
		}
		return getHibernateTemplate().findByCriteria(criteria, page * pageSize, pageSize);
	}

	public List<UserProfile> getAllEmployeesByCompanyId(Long companyid) {
		// TODO Auto-generated method stub
		return null;
	}

}
